package org.jumiz.javafx.client.pages.login;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import javafx.scene.layout.GridPane;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jumiz.javafx.business.ApplicationContext;
import org.jumiz.javafx.business.sys.entity.UserEntity;
import org.jumiz.javafx.business.sys.repository.UserRepository;
import org.jumiz.javafx.client.pages.commonents.JumizForm1;
import org.jumiz.javafx.client.pages.commonents.JumizStackPane;
import org.jumiz.javafx.client.pages.commonents.LayoutPane;
import org.jumiz.javafx.client.util.FileUtil;
import org.jumiz.javafx.client.util.SwitchScene;

import java.util.List;
import java.util.Map;

/**
 * 登录页面
 */
public class LoginPage extends JumizStackPane {

    private static Logger logger = LogManager.getLogger(LoginPage.class);

    public LoginPage() {
        super();
        this.init();
    }

    private void init() {
        // 背景图
        this.withBackgroundImage("static/images/login-bg.jpeg");
        // 登录表单
        this.drawForm();
        this.getChildren().add(drawForm());
    }

    private GridPane drawForm() {
        JumizForm1 form = new JumizForm1();

        String json = FileUtil.loadJson("static/pages/login/loginPage.json");
        JSONArray array = JSON.parseArray(json);
        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            form.addTextField(obj.getString("label"));
        }

        form.addSubmitButton("保存", event -> {
            Map<String, String> formData = form.getFormData();

            UserRepository userRepository = ApplicationContext.getBean(UserRepository.class);
            List<UserEntity> list = userRepository.findAll();
            logger.debug(list);

            System.out.println(JSON.toJSONString(formData));
            SwitchScene.switchScene(new LayoutPane());
        });

        return form;
    }

}
